﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using GFE.SharePoint.Interfaces;
using GFE.SharePoint.Attributes;

namespace GFE.SharePoint.Lazy
{
    public class GFEJSONLazy<T> : IGFELazy<T>
    {
        Type _viewClass = default(Type);
        Type _presenterClass = default(Type);
        GFELazy<T> _lazy = default(GFELazy<T>);
        public GFEJSONLazy(GFELazy<T> lazy, Type ViewClass, Type PresenterClass)
        {
            _lazy = lazy;
            _viewClass = ViewClass;
            _presenterClass = PresenterClass;
        }

        public T Value
        {
            get { return _lazy.Value; }
        }

        public MethodInfo GetMethodInfo(string MethodName)
        {
            return _viewClass.GetMEFMethodDictionay<GFEJSONMethodAttribute>()
                                        .Where(x => x.Key == MethodName)
                                        .Select(x => x.Value)
                                        .FirstOrDefault();
        }

        public object InvokeByName(string MethodName, object[] MethodParameters)
        {
            var JSONMethod =_viewClass.GetMEFMethodDictionay<GFEJSONMethodAttribute>()
                                        .Where(x => x.Key == MethodName)
                                        .Select(x => x.Value)
                                        .FirstOrDefault();
            if (JSONMethod == default(object)) return JSONMethod;

            Object ViewObject = Activator.CreateInstance(_viewClass);
            Object PresenterObject = Activator.CreateInstance(_presenterClass, new object[] {ViewObject});
            
            // INIT method call missing!!!!!
            
            var result = JSONMethod.Invoke(ViewObject, MethodParameters);
            if (result == null && JSONMethod.ReturnType == typeof(void))
                result = "Success";
            return result;
        }


        public int LoadOrder
        {
            get { throw new NotImplementedException(); }
        }
    }
}
